package com.yunxi.service.dubboService.impl.sat;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.customer.pojo.CustomerVO;
import com.yunxi.customer.service.CustomerDubboService;
import com.yunxi.dealer.pojo.AreaManagerVO;
import com.yunxi.dealer.pojo.PartnerVO;
import com.yunxi.dealer.service.AreaManagerDubboService;
import com.yunxi.dealer.service.PartnerDubboService;
import com.yunxi.hubToBiz.pojo.CustomerTestDriveVO;
import com.yunxi.model.order.OrderCustomer;
import com.yunxi.model.sat.MsgTemplate;
import com.yunxi.model.sat.SatConfig;
import com.yunxi.model.sat.SatCustomerClue;
import com.yunxi.model.sat.SatMess;
import com.yunxi.order.pojo.OrderCustomerVO;
import com.yunxi.sat.pojo.SatCustomerClueVO;
import com.yunxi.sat.pojo.SatMessAddVO;
import com.yunxi.sat.service.SatCustomerClueDubboService;
import com.yunxi.sat.service.SatCustomerFollowDubboService;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.OrderCustomerService;
import com.yunxi.service.localService.sat.*;
import com.yunxi.sys.pojo.StaffVO;
import com.yunxi.sys.service.StaffDubboService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;


/**
 * <p>
 * 客户线索 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-07-10
 */
public class SatCustomerClueDubboServiceImpl implements SatCustomerClueDubboService {
   private static final Logger logger = LoggerFactory.getLogger(SatCustomerClueDubboServiceImpl.class);
   @Autowired
   @Qualifier(value = "satCustomerClueServiceImpl")
   SatCustomerClueService satCustomerClueService;

   @Autowired
   @Qualifier(value = "codeCreateServiceImpl")
   CodeCreateService codeCreateService;

   @Autowired
   @Qualifier(value = "satConfigServiceImpl")
   SatConfigService satConfigService;

   @Autowired
   OrderCustomerService orderCustomerServiceImpl;

   @Autowired
   PartnerDubboService partnerDubboServiceImpl;

   @Autowired
   AreaManagerDubboService areaManagerDubboServiceImpl;

   @Autowired
   SatMessService satMessServiceImpl;

   @Autowired
   @Qualifier(value = "staffDubboServiceBiz")
   StaffDubboService staffDubboService;

   @Autowired
   @Reference(version = "1.0.0")
   CustomerDubboService customerDubboServiceImpl;

   @Autowired
   @Qualifier(value = "msgTemplateServiceImpl")
   MsgTemplateService msgTemplateService;

   @Autowired
   SatCustomerFollowDubboService satCustomerFollowDubboServiceImpl;

   @Autowired
   @Qualifier(value = "satTestDriveServiceImpl")
   SatTestDriveService satTestDriveService;

   @Override
   public SatCustomerClueVO getById(String id) throws Exception {
      SatCustomerClue satCustomerClue = satCustomerClueService.getById(id);
      if (satCustomerClue != null) {
         SatCustomerClueVO satCustomerClueVO = new SatCustomerClueVO();
         BeanUtils.copyProperties(satCustomerClue, satCustomerClueVO);
         return satCustomerClueVO;
      } else {
         throw new Exception("操作失败,无法根据id:" + id + "找到对应客户线索!");
      }
   }

   @Override
   public void saveOrUpdate(SatCustomerClueVO satCustomerClueVO) {
      SatCustomerClue satCustomerClue = new SatCustomerClue();
      BeanUtils.copyProperties(satCustomerClueVO, satCustomerClue);
      if (StringUtils.isEmpty(satCustomerClueVO.getClueNo())) {
         String cc = codeCreateService.createCode("CC", 4);//线索编号
         satCustomerClue.setClueNo(cc);
      }
      satCustomerClueService.saveOrUpdate(satCustomerClue);
   }

   /**
    * 领取线索
    *
    * @param clueId
    * @param loginInfo
    * @throws Exception
    */
   @Override
   @Transactional
   public void getClue(String clueId, LoginInfo loginInfo) throws Exception {
      if (StringUtils.isEmpty(loginInfo.getUserCode())) throw new Exception("当前登陆账号为空" + loginInfo.getUserCode());
      if (StringUtils.isEmpty(loginInfo.getPartnerCode())) throw new Exception("当前渠道商编号为空" + loginInfo.getPartnerCode());
      SatCustomerClueVO satCustomerClueVO = getSatCustomerClueVO(clueId, loginInfo);
      satCustomerClueVO.setGetUser(loginInfo.getUserCode());
      satCustomerClueService.getClue(satCustomerClueVO, loginInfo);

      SatCustomerClueVO clueVO = this.getById(clueId);
      if (clueVO == null || StringUtils.isEmpty(clueVO.getClueType())) throw new Exception("当前线索类型为空" + clueId);
      clueVO.setCustStatus(0);//意向类型
      if ("3".equals(clueVO.getClueType())) {
         clueVO.setCustStatus(1);//订单类型

         //如果是订单 同步领取订单
         OrderCustomer orderCustomer = new OrderCustomer();
         orderCustomer.setSalesConsultantNo(loginInfo.getUserCode());
         orderCustomer.setPartnerCode(loginInfo.getPartnerCode());
         QueryWrapper<OrderCustomer> queryWrapper = new QueryWrapper<>();
         queryWrapper.eq("ORDER_CUSTOMER_NO", clueVO.getBusinessKey());
         orderCustomerServiceImpl.update(orderCustomer, queryWrapper);

         //如果大定已付款 同步生成待交车信息
         List<OrderCustomer> orderCustomerList = orderCustomerServiceImpl.list(queryWrapper);
         if (orderCustomerList!=null && orderCustomerList.size()>0){
            OrderCustomer orderCust = orderCustomerList.get(0);
            if (orderCust.getBusType().intValue()==1){
               satCustomerFollowDubboServiceImpl.orderCustomerFollow(orderCust.getOrderCustomerId(),null,false,true,loginInfo  );
            }
         }


//         //线索领取时,需同步客户信息并生成消息提醒
//         if (StringUtils.isNotEmpty(clueVO.getBusinessKey())){
//            OrderCustomerVO vo = new OrderCustomerVO();
//            vo.setOrderCustomerNo(clueVO.getBusinessKey());
//            List<OrderCustomerVO> orderCustomerVOList = orderCustomerServiceImpl.listByVo(vo);
//            if (orderCustomerVOList!=null && orderCustomerVOList.size()>0){
//               OrderCustomerVO orderCustomerVO = orderCustomerVOList.get(0);
//               if (StringUtils.isNotEmpty(orderCustomerVO.getPartnerCode())){
//                  //同步客户信息
//                  syncCustomer(orderCustomerVO, loginInfo);
//                  //生成消息提醒  消息提醒是针对所有销售顾问bug,此时应该发送给单个人 暂时注释
////                  LoginInfo info = new LoginInfo();
////                  info.setPartnerCode(orderCustomerVO.getPartnerCode());
////                  ApiResult apiResult = staffDubboService.listStaffByRoleCode("rolePartnerSale", info);
////                  if (apiResult.getData()!=null){
////                     List<StaffVO> staffVOList = (List<StaffVO>) apiResult.getData();
////                     if (staffVOList!=null && staffVOList.size()>0){
////                        StaffVO staffVO = staffVOList.get(0);
////                        loginInfo.setUserCode(staffVO.getAccountNo());
////                     }
////                  }
////                  sendMsg(loginInfo, orderCustomerVO, "3", 3,"rolePartnerSale");
//               }
//            }
//         }
         clueVO.setCustStatus(1);
      }
      //如果领取试驾线索,则根据线索中的客户编号,查询渠道代码为空的试驾信息
//      if ("2".equals(clueVO.getClueType())) {
//         //查询符合条件的试驾信息,写入线索所属渠道代码
//         satCustomerClueService.setTestDrivePartnerCode(clueId,loginInfo.getUserCode());
//      }
      //同步创建或更新客户
      updateCustomer(clueId, loginInfo, clueVO,loginInfo.getUserCode());

   }

   private void updateCustomer(String clueId, LoginInfo loginInfo, SatCustomerClueVO clueVO,String getUser) throws Exception {
      if (StringUtils.isEmpty(clueVO.getCustomerNo())) throw new Exception("线索中客户编号为空" + clueId);
      CustomerVO customerVO = new CustomerVO();
      CustomerVO custVO = customerDubboServiceImpl.load(clueVO.getCustomerNo(),loginInfo.getPartnerCode(), loginInfo);
      if (custVO != null) {
         customerVO.setCustomerId(custVO.getCustomerId());
      }else {
         customerVO.setCreateBy(loginInfo.getUserCode());
         customerVO.setSource(1);
      }
      customerVO.setPartnerCode(loginInfo.getPartnerCode());
      customerVO.setSalesConsultantNo(getUser);
      customerVO.setCustomerNo(clueVO.getCustomerNo());
      customerVO.setName(clueVO.getCustomerName());
      customerVO.setPhone(clueVO.getTel());
      customerVO.setTelephone(clueVO.getTel());
      customerVO.setProvince(clueVO.getProvince());
      customerVO.setCity(clueVO.getCity());

      if (clueVO.getCustStatus()!=null){
         customerVO.setCustStatus(clueVO.getCustStatus());
      }else {
         customerVO.setCustStatus(4);
      }
      customerVO.setSex(clueVO.getSex());
      customerVO.setRegion(clueVO.getRegion());
      customerVO.setVehicleCode(clueVO.getVehicleCode());
      if (StringUtils.isEmpty(clueVO.getLevel())){
          if ("3".equals(clueVO.getClueType())) {
              customerVO.setLevel("1");
          } else {
              customerVO.setLevel("6");
          }
      }else {
          customerVO.setLevel(clueVO.getLevel());
      }
      customerVO.setUserSource1(clueVO.getUserSource1());
      customerVO.setUserSource2(clueVO.getUserSource2());
      customerVO.setUserSource3(clueVO.getUserSource3());
      customerDubboServiceImpl.updateOrSave(customerVO);
   }

   /**
    * 分配线索给销售顾问
    *
    * @param clueId
    * @param loginInfo
    * @throws Exception
    */
   @Override
   public void assignClue(String clueId, String getUser, LoginInfo loginInfo) throws Exception {
      if (StringUtils.isEmpty(loginInfo.getUserCode())) throw new Exception("当前登陆账号为空" + loginInfo.getUserCode());
      if (StringUtils.isEmpty(loginInfo.getPartnerCode())) throw new Exception("当前渠道商编号为空" + loginInfo.getPartnerCode());
      if (StringUtils.isEmpty(getUser)) throw new Exception("销售顾问为空" + getUser);

      SatCustomerClueVO satCustomerClueVO = getSatCustomerClueVO(clueId, loginInfo);
      satCustomerClueVO.setGetUser(getUser);
      satCustomerClueVO.setAssignUser(loginInfo.getUserCode());
//        String userCode = satCustomerClueService.getUserCodeByName(getUser);
      satCustomerClueVO.setPartnerCode(loginInfo.getPartnerCode());
      satCustomerClueVO.setSalesConsultantNo(getUser);
      satCustomerClueVO.setOperaRoleCode(loginInfo.getRoleCode());
      SatCustomerClueVO clueVO = this.getById(clueId);
      satCustomerClueService.assignClue(satCustomerClueVO);
      if (clueVO == null || StringUtils.isEmpty(clueVO.getClueType())) throw new Exception("当前线索类型为空" + clueId);
      clueVO.setCustStatus(0);//意向类型

      if ("3".equals(clueVO.getClueType())) {
         clueVO.setCustStatus(1);//订单类型

         OrderCustomer orderCustomer = new OrderCustomer();
         orderCustomer.setSalesConsultantNo(getUser);
         orderCustomer.setPartnerCode(loginInfo.getPartnerCode());
         QueryWrapper<OrderCustomer> queryWrapper = new QueryWrapper<>();
         queryWrapper.eq("ORDER_CUSTOMER_NO", clueVO.getBusinessKey());
         orderCustomerServiceImpl.update(orderCustomer, queryWrapper);

         //如果大定已付款 同步生成待交车信息
         List<OrderCustomer> orderCustomerList = orderCustomerServiceImpl.list(queryWrapper);
         if (orderCustomerList!=null && orderCustomerList.size()>0){
            OrderCustomer orderCust = orderCustomerList.get(0);
            if (orderCust.getBusType().intValue()==1){
               LoginInfo info = new LoginInfo();
               info.setUserCode(getUser);
               satCustomerFollowDubboServiceImpl.orderCustomerFollow(orderCust.getOrderCustomerId(),null,false,true ,info );
            }
         }

         //线索领取时,需同步客户信息并生成消息提醒
         /*if (StringUtils.isNotEmpty(clueVO.getBusinessKey())) {
            OrderCustomerVO vo = new OrderCustomerVO();
            vo.setOrderCustomerNo(clueVO.getBusinessKey());
            List<OrderCustomerVO> orderCustomerVOList = orderCustomerServiceImpl.listByVo(vo);
            if (orderCustomerVOList != null && orderCustomerVOList.size() > 0) {
               OrderCustomerVO orderCustomerVO = orderCustomerVOList.get(0);
               if (StringUtils.isNotEmpty(orderCustomerVO.getPartnerCode())) {

                  //销售经理分配给销售顾问时,在同步信息的时候,是根据logininfo的usercode来进行绑定销售顾问的
                  //所以需要将usercode修改成被分配的销售顾问
                  loginInfo.setUserCode(getUser);
                  //同步客户信息
                  syncCustomer(orderCustomerVO, loginInfo);
                  //生成消息提醒 消息提醒是针对所有销售顾问bug,此时应该发送给单个人 暂时注释
//                  LoginInfo info = new LoginInfo();
//                  info.setPartnerCode(orderCustomerVO.getPartnerCode());
//                  ApiResult apiResult = staffDubboService.listStaffByRoleCode("rolePartnerSale", info);
//                  if (apiResult.getData()!=null){
//                     List<StaffVO> staffVOList = (List<StaffVO>) apiResult.getData();
//                     if (staffVOList!=null && staffVOList.size()>0){
//                        StaffVO staffVO = staffVOList.get(0);
//                        loginInfo.setUserCode(staffVO.getAccountNo());
//                     }
//                  }
//                  sendMsg(loginInfo, orderCustomerVO, "3", 3,"rolePartnerSale");
               }
            }
         }*/
      }
      //如果领取试驾线索,则根据线索中的客户编号,查询渠道代码为空的试驾信息
//      if ("2".equals(clueVO.getClueType())) {
//         //查询符合条件的试驾信息,写入线索所属渠道代码
//         satCustomerClueService.setTestDrivePartnerCode(clueId,getUser);
//      }
      //同步创建或更新客户
      LoginInfo info = new LoginInfo();
      info.setUserCode(getUser);
      info.setPartnerCode(loginInfo.getPartnerCode());
      updateCustomer(clueId, info, clueVO,getUser);
   }

   /**
    * 分配线索给渠道商
    *
    * @param clueId
    * @param partnerCode
    * @param loginInfo
    * @throws Exception
    */
   @Override
   public void assignClueToP(String clueId, String partnerCode, LoginInfo loginInfo) throws Exception {
      SatCustomerClueVO satCustomerClueVO = getSatCustomerClueVO(clueId, loginInfo);
      satCustomerClueVO.setPartnerCode(partnerCode);
      satCustomerClueVO.setAssignUser(loginInfo.getUserCode());
      SatCustomerClue satCustomerClue = satCustomerClueService.getById(satCustomerClueVO.getClueId());
      if(satCustomerClue != null){
         //校验已领取的线索不可再次分配
         Integer isGet = satCustomerClue.getIsGet();
         if (isGet != null && isGet.equals(1)) {
            throw new Exception("操作失败,线索已被领取!");
         }
         satCustomerClue.setPartnerCode(satCustomerClueVO.getPartnerCode());
         satCustomerClue.setAssignUser(satCustomerClueVO.getAssignUser());
         satCustomerClueService.saveOrUpdate(satCustomerClue);

         //分配线索给渠道时,自动将该客户线索分配给该渠道下这名客户的所属销售顾问
         CustomerTestDriveVO customerTestDriveVO = new CustomerTestDriveVO();
         customerTestDriveVO.setUserId(satCustomerClue.getCustomerNo());
         customerTestDriveVO.setKunnrcode(satCustomerClueVO.getPartnerCode());
         List<String> list = satTestDriveService.getCustomerSales(customerTestDriveVO);
         if(list != null && list.size() > 0){
            LoginInfo loginInfo1 = new LoginInfo();
            loginInfo1.setPartnerCode(partnerCode);
            assignClue(clueId,list.get(0),loginInfo1);
         }
      }
      else {
         throw new Exception("操作失败,无法根据id:找到对应客户线索!");
      }
   }

   @Override
   public PageInfo<SatCustomerClueVO> findPageByVO(SatCustomerClueVO satCustomerClueVO, Integer pageNum, Integer pageSize, LoginInfo loginInfo) throws InvocationTargetException, IllegalAccessException {
      //1.查询销售助手配置,线索超期时间
//      Integer clueOverTime = null;
//
//      QueryWrapper<SatConfig> queryWrapper = new QueryWrapper<>();
//      if (StringUtils.isNotEmpty(satCustomerClueVO.getPartnerCode())) {
//         queryWrapper.eq("PARTNER_CODE", satCustomerClueVO.getPartnerCode());
//      }

      satCustomerClueVO.setUserCode(loginInfo.getUserCode());

      logger.warn("PartnerCode ======= " + loginInfo.getPartnerCode());
      if (StringUtils.isNotEmpty(loginInfo.getPartnerCode())) {
         satCustomerClueVO.setIsPartner(1);//是渠道商
      } else {
         satCustomerClueVO.setIsPartner(0);//不是渠道商,厂家
      }

      //销售顾问
      if (StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())) {
//         SatConfig one = satConfigService.getOne(queryWrapper);
//         if (one != null) {
//            clueOverTime = one.getClueOverTime();
//            satCustomerClueVO.setClueOverHours(new Double("0.5"));//销售顾问,0.5小时,暂时写死
//         }
         if (satCustomerClueVO.getIsGet() != null && satCustomerClueVO.getIsGet() == 0)
            satCustomerClueVO.setClueOverHours(30);//销售顾问,0.5小时,暂时写死
         satCustomerClueVO.setOperaRoleCode(DictConstant.USER_ROLE_SALES);
      }

      //销售经理
      if (StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_MANAGER.equals(loginInfo.getRoleCode())) {
//         if(satCustomerClueVO.getIsGet() != null && satCustomerClueVO.getIsGet().equals(0)){
//            satCustomerClueVO.setIsGet(2);
//         }
//
//         SatConfig one = satConfigService.getOne(queryWrapper);
//         if (one != null) {
//            satCustomerClueVO.setClueOverHours(new Double("1"));//销售经理默认1小时,暂时写死
//         }

         if (satCustomerClueVO.getIsGet() != null && satCustomerClueVO.getIsGet() == 0)
//            satCustomerClueVO.setClueOverHours(60);//销售经理默认1小时,暂时写死
         satCustomerClueVO.setOperaRoleCode(DictConstant.USER_ROLE_MANAGER);
      }

      //大区经理
      if (StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_AREAMANAGER.equals(loginInfo.getRoleCode())) {//大区经理
         AreaManagerVO vo = new AreaManagerVO();
         vo.setUserCode(loginInfo.getUserCode());
         vo.setPCode("0");//大区
         List<AreaManagerVO> list = areaManagerDubboServiceImpl.listByVo(vo);
         if (list == null || list.size() <= 0) {
            return null;
         }
         satCustomerClueVO.setOperaRoleCode(DictConstant.USER_ROLE_AREAMANAGER);
         satCustomerClueVO.setClueOverHours(30); //区域经理查询超时时间为销售顾问未领取的时间30分钟
      }

      //城市辅导员
      if (StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_CITYMANAGER.equals(loginInfo.getRoleCode())) {//城市辅导经理
         satCustomerClueVO.setLoginUserCode(loginInfo.getUserCode());
         satCustomerClueVO.setPcode("");

         //城市辅导员如果没有配置所负责的城市,则返回空给前端
         AreaManagerVO vo = new AreaManagerVO();
         vo.setUserCode(loginInfo.getUserCode());
         List<AreaManagerVO> list = areaManagerDubboServiceImpl.listByUserCode(vo);
         if (list == null || list.size() <= 0) {
            return null;
         }
         satCustomerClueVO.setOperaRoleCode(DictConstant.USER_ROLE_CITYMANAGER);
         satCustomerClueVO.setClueOverHours(30);//城市辅导员查询超时时间为销售顾问未领取的时间30分钟
      }
      PageInfo<SatCustomerClueVO> pageInfo = satCustomerClueService.pageByVo(satCustomerClueVO, pageNum, pageSize);
      return pageInfo;
   }

   /**
    * 今日待分配线索数
    *
    * @param loginInfo
    * @return
    * @throws Exception
    */
   @Override
   public Integer todayClueCount(LoginInfo loginInfo) throws Exception {
      Object partner = loginInfo.getPartner();
      SatCustomerClueVO satCustomerClueVO = new SatCustomerClueVO();
      if (partner != null) {
         PartnerVO partnerVO = JSONObject.parseObject(JSONObject.toJSONString(partner), PartnerVO.class);
         satCustomerClueVO.setPartnerCode(partnerVO.getPartnerCode());
      }

      QueryWrapper<SatConfig> queryWrapper = new QueryWrapper<>();
      if (StringUtils.isNotEmpty(satCustomerClueVO.getPartnerCode())) {
         queryWrapper.eq("PARTNER_CODE", satCustomerClueVO.getPartnerCode());
      }
//      SatConfig one = satConfigService.getOne(queryWrapper);
//      if (one != null) {
////         clueOverTime = one.getClueOverTime();
//         satCustomerClueVO.setClueOverHours(new Double(one.getClueOverTime()));
//      }

      //销售顾问
      if (StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())) {
         satCustomerClueVO.setClueOverHours(30);//销售顾问,0.5小时,暂时写死
      }

      //销售经理
      if (StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_MANAGER.equals(loginInfo.getRoleCode())) {
         satCustomerClueVO.setClueOverHours(60);//销售顾问,1小时,暂时写死
      }
      if(StringUtils.isNotEmpty(loginInfo.getRoleCode()) && (DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode()) || DictConstant.USER_ROLE_MANAGER.equals(loginInfo.getRoleCode()))){
         return satCustomerClueService.todayClueCount(satCustomerClueVO);
      }
      else{
         return null;
      }
   }

   @Override
   public void updateIsCreatedCust(String id) {
      SatCustomerClue satCustomerClue = new SatCustomerClue();
      satCustomerClue.setClueId(id);
      satCustomerClue.setIsCreatedCust(1);
      satCustomerClueService.updateById(satCustomerClue);
   }


   /**
    * 大区/小区 经理分配线索
    *
    * @param list
    * @param partnerCode
    * @param userCode
    * @throws Exception
    */
   @Override
   public void areaManager(List<String> list, String partnerCode, String userCode, LoginInfo loginInfo) throws Exception {
      if (list == null || list.size() <= 0) throw new Exception("操作失败,线索主键集合为空!");
      if (StringUtils.isEmpty(partnerCode)) throw new Exception("操作失败,分配的渠道商代码为空!");

//      List<OrderCustomer> orderCustomerList = new ArrayList<>();
      Collection<SatCustomerClue> satCustomerClues = satCustomerClueService.listByIds(list);
      ArrayList<String> clueIds = new ArrayList<>();
      //查询该渠道商下所有所有销售经理
      LoginInfo loginInfo1 = new LoginInfo();
      loginInfo1.setPartnerCode(partnerCode);
      ApiResult apiResult = staffDubboService.listStaffByRoleCode(DictConstant.USER_ROLE_MANAGER, loginInfo1);
      Object data = apiResult.getData();
      List<StaffVO> staffVOList = new ArrayList<>();
      if (data != null) {
         staffVOList = (List<StaffVO>) apiResult.getData();
      }

      //获取消息模板
      QueryWrapper<MsgTemplate> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("TYPE", 2);
      MsgTemplate msgTemplate = msgTemplateService.getOne(queryWrapper);

      for (SatCustomerClue satCustomerClue : satCustomerClues) {
         satCustomerClue.setPartnerCode(partnerCode);
         satCustomerClue.setBigRegionManager(userCode);
         satCustomerClue.setAssignUser(userCode);
         satCustomerClue.setAssignDate(new Date());
         satCustomerClue.setIsRemind(0);
         satCustomerClue.setIsRemindManager(0);
         clueIds.add(satCustomerClue.getClueId());
         //如果为订单类型的线索  同步分配订单
//         if ("3".equals(satCustomerClue.getClueType())) {
//            OrderCustomer orderCustomer = new OrderCustomer();
//            orderCustomer.setOrderCustomerNo(satCustomerClue.getBusinessKey());
//            orderCustomer.setPartnerCode(partnerCode);
//            orderCustomerList.add(orderCustomer);
//         }
         //分配线索给渠道时,自动将该客户线索分配给该渠道下这名客户的所属销售顾问
         CustomerTestDriveVO customerTestDriveVO = new CustomerTestDriveVO();
         customerTestDriveVO.setUserId(satCustomerClue.getCustomerNo());
         customerTestDriveVO.setKunnrcode(partnerCode);
         List<String> saleList = satTestDriveService.getCustomerSales(customerTestDriveVO);
         if(saleList != null && saleList.size() > 0){
            LoginInfo loginInfo2 = new LoginInfo();
            loginInfo2.setPartnerCode(partnerCode);
            loginInfo2.setUserCode(saleList.get(0));
            loginInfo2.setRoleCode(loginInfo.getRoleCode());
            assignClue(satCustomerClue.getClueId(), saleList.get(0), loginInfo2);
         }

      }
      //查询该渠道商下所有所有销售经理,推送消息
      pushMsgToM(satCustomerClues, staffVOList, msgTemplate);
      satCustomerClueService.updateBatch(satCustomerClues);
//      if (orderCustomerList.size() > 0) {
//         orderCustomerServiceImpl.assignBatch(orderCustomerList);
//      }
   }

//   private void sendMsg(LoginInfo loginInfo, OrderCustomerVO orderCustomerVO, String msgType, Integer templateType, String receiveRoleCode) throws InvocationTargetException, IllegalAccessException {
//      SatMessAddVO satMessAddVO = new SatMessAddVO();
//      satMessAddVO.setType(msgType);
//      satMessAddVO.setTemplateType(templateType);
//      CustomerVO customerVO = customerDubboServiceImpl.load(orderCustomerVO.getCustomerNo(), loginInfo);
//      if (customerVO != null) {
//         satMessAddVO.setCustomerName(customerVO.getName());
//         satMessAddVO.setCustomerNo(customerVO.getCustomerNo());
//      }
//      satMessAddVO.setSalesConsultantNo(loginInfo.getUserCode());
//      satMessAddVO.setOperaRoleCode(loginInfo.getRoleCode());
//      satMessAddVO.setReceiveRoleCode(receiveRoleCode);
//      satMessAddVO.setBusinessKey(orderCustomerVO.getOrderCustomerNo());
//      satMessServiceImpl.newMess(satMessAddVO);
//   }


   @Deprecated
   private void syncCustomer(OrderCustomerVO orderCustomerVO, LoginInfo loginInfo) throws Exception {

      if (StringUtils.isEmpty(loginInfo.getPartnerCode())) {
         loginInfo.setPartnerCode(orderCustomerVO.getPartnerCode());
      }
      CustomerVO v1 = customerDubboServiceImpl.getByPhone(orderCustomerVO.getCustomerMobile(), loginInfo.getPartnerCode());
      if (v1 != null) {
         v1.setCustomerNo(orderCustomerVO.getCustomerNo());
         v1.setName(orderCustomerVO.getCustomerName());
         v1.setTelephone(orderCustomerVO.getCustomerMobile());
         v1.setPhone(orderCustomerVO.getCustomerMobile());
      } else {
         //本地创建 并上传到URM
         v1 = new CustomerVO();
         v1.setName(orderCustomerVO.getCustomerName());
         v1.setTelephone(orderCustomerVO.getCustomerMobile());
         v1.setPhone(orderCustomerVO.getCustomerMobile());
         v1.setCustStatus(1); //0意向 1订单 2战败 3基盘 4线索
         v1.setPartnerCode(orderCustomerVO.getPartnerCode());


      }
      ApiResult apiResult = customerDubboServiceImpl.saveOrUpdate(v1, loginInfo);
      if (apiResult.getCode() == 200) {
         if (apiResult.getData() != null) {
            String ordercustomerNoURM = (String) apiResult.getData();
            orderCustomerVO.setCustomerId(ordercustomerNoURM);
            orderCustomerVO.setCustomerNo(ordercustomerNoURM);
         }
      }
   }

   /**
    * 自动分配线索
    *
    * @param list
    * @param loginInfo
    * @throws Exception
    */
   @Override
   public void autoAssign(List<SatCustomerClueVO> list, LoginInfo loginInfo) throws Exception {
      if (list == null || list.size() <= 0) throw new Exception("操作失败,线索为空!");

      List<String> clueTypeList = new ArrayList<>();
      //获取所有线索类型
      for (int i = 0; i < list.size(); i++) {
         if (StringUtils.isNotEmpty(list.get(i).getClueType())){
            if (!clueTypeList.contains(list.get(i).getClueType())) {
               clueTypeList.add(list.get(i).getClueType());
            }
         }
      }

      //获取消息模板
      QueryWrapper<MsgTemplate> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("TYPE", 2);
      MsgTemplate msgTemplate = msgTemplateService.getOne(queryWrapper);

      List<SatCustomerClueVO> satCustomerClueList = new ArrayList<>();
      for (String clueType : clueTypeList) {
         //获取同一类型的线索
         for (int i = 0; i < list.size(); i++) {
            if (clueType.equals(list.get(i).getClueType())) {
               satCustomerClueList.add(list.get(i));
            }
         }
         //分配线索
         List<SatCustomerClue> satCustomerClues = new ArrayList<>();
//         List<OrderCustomer> orderCustomerList = new ArrayList<>();
         List<StaffVO> staffVOList = new ArrayList<>();
         for (int i = 0; i < satCustomerClueList.size(); i++) {
            SatCustomerClueVO satCustomerClueVO = satCustomerClueList.get(i);
            String leastPartner = partnerDubboServiceImpl.leastPartner(satCustomerClueVO.getClueType(), satCustomerClueVO.getProvince(), satCustomerClueVO.getVehicleCode(), satCustomerClueVO.getCity());
            if (StringUtils.isEmpty(leastPartner)) {
               continue;
            }
            SatCustomerClue satCustomerClue = new SatCustomerClue();
            BeanUtils.copyProperties(satCustomerClueVO, satCustomerClue);
            satCustomerClue.setPartnerCode(leastPartner);
            satCustomerClue.setBigRegionManager(loginInfo.getUserCode());
            satCustomerClue.setAssignUser(loginInfo.getUserCode());
            satCustomerClue.setAssignDate(new Date());
            satCustomerClue.setIsRemind(0);
            satCustomerClue.setIsRemindManager(0);
            satCustomerClueService.updateById(satCustomerClue);
            satCustomerClues.add(satCustomerClue);
            //如果为订单类型的线索  同步分配订单
//            if ("3".equals(satCustomerClue.getClueType())) {
//               OrderCustomer orderCustomer = new OrderCustomer();
//               orderCustomer.setOrderCustomerNo(satCustomerClue.getBusinessKey());
//               orderCustomer.setPartnerCode(leastPartner);
//               orderCustomerList.add(orderCustomer);
//            }
            //分配线索给渠道时,自动将该客户线索分配给该渠道下这名客户的所属销售顾问
            CustomerTestDriveVO customerTestDriveVO = new CustomerTestDriveVO();
            customerTestDriveVO.setUserId(satCustomerClue.getCustomerNo());
            customerTestDriveVO.setKunnrcode(leastPartner);
            List<String> saleList = satTestDriveService.getCustomerSales(customerTestDriveVO);
            if(saleList != null && saleList.size() > 0){
               LoginInfo loginInfo2 = new LoginInfo();
               loginInfo2.setPartnerCode(leastPartner);
               loginInfo2.setUserCode(loginInfo.getUserCode());
               loginInfo2.setRoleCode(loginInfo.getRoleCode());
               assignClue(satCustomerClue.getClueId(), saleList.get(0), loginInfo2);
            }

            //查询该渠道商下所有所有销售经理,推送消息
            LoginInfo loginInfo1 = new LoginInfo();
            loginInfo1.setPartnerCode(leastPartner);
            ApiResult apiResult = staffDubboService.listStaffByRoleCode(DictConstant.USER_ROLE_MANAGER, loginInfo1);
            Object data = apiResult.getData();
            if (data != null) {
               List<StaffVO> staffVOS = (List<StaffVO>) apiResult.getData();
               staffVOList.addAll(staffVOS);
            }

         }
//         satCustomerClueService.updateBatchById(satCustomerClues);
//         if (orderCustomerList.size() > 0) {
//            orderCustomerServiceImpl.assignBatch(orderCustomerList);
//         }
         pushMsgToM(satCustomerClues, staffVOList, msgTemplate);

         satCustomerClueList.clear();
         satCustomerClues.clear();
//         orderCustomerList.clear();
      }
   }

   @Override
   public void updateByBusinessKey(SatCustomerClueVO satCustomerClueVO) {
      SatCustomerClue satCustomerClue = new SatCustomerClue();
      BeanUtils.copyProperties(satCustomerClueVO,satCustomerClue);
      QueryWrapper<SatCustomerClue> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("BUSINESS_KEY",satCustomerClueVO.getBusinessKey());
      satCustomerClueService.update(satCustomerClue,queryWrapper);
   }

   /**
    * 推送消息到销售经理
    *
    * @param
    * @param
    * @throws InvocationTargetException
    * @throws IllegalAccessException
    */
   private void pushMsgToM(Collection<SatCustomerClue> satCustomerClues, List<StaffVO> staffVOList, MsgTemplate msgTemplate) throws InvocationTargetException, IllegalAccessException {
      List<SatMess> satMessList = new ArrayList<>();
      for (SatCustomerClue satCustomerClue : satCustomerClues) {
         for (StaffVO vo : staffVOList) {
            SatMess satMess = new SatMess();
            satMess.setType("1");//线索分配
            satMess.setCustomerNo(satCustomerClue.getCustomerNo());
            satMess.setCustomerName(satCustomerClue.getCustomerName());
            satMess.setSalesConsultantNo(vo.getAccountNo());
            satMess.setOperaRoleCode(DictConstant.USER_ROLE_AREAMANAGER);
            satMess.setReceiveRoleCode(DictConstant.USER_ROLE_MANAGER);
            satMess.setBusinessKey(satCustomerClue.getBusinessKey());
            satMess.setInfo(msgTemplate.getInfo());
            satMessList.add(satMess);
         }
      }

      System.out.println("开始发送" + System.currentTimeMillis());
      satMessServiceImpl.newMess2(satMessList);
      System.out.println("发送完成" + System.currentTimeMillis());
   }


   private SatCustomerClueVO getSatCustomerClueVO(String clueId, LoginInfo loginInfo) throws InvocationTargetException, IllegalAccessException {
      SatCustomerClueVO satCustomerClueVO = new SatCustomerClueVO();
      satCustomerClueVO.setClueId(clueId);
      satCustomerClueVO.setPartnerCode(loginInfo.getPartnerCode());
      String accountNo = loginInfo.getUserCode();
      satCustomerClueVO.setSalesConsultantNo(accountNo);

      satCustomerClueVO.setCreateBy(loginInfo.getUserCode());
      satCustomerClueVO.setUpdateBy(loginInfo.getUserCode());
      return satCustomerClueVO;
   }

}
